<template>
	<view class="follow-page">
		<!-- Tab 切换 -->
		<up-tabs 
			v-if="tabList.length > 0"
			:list="tabList" 
			@change="handleTabChange" 
			:current="currentTab"
			lineColor="#36d399"
		></up-tabs>

		<!-- 列表容器 -->
		<scroll-view scroll-y class="scroll-container" @scrolltolower="loadMore" :refresher-enabled="true"
			:refresher-triggered="refreshing" @refresherrefresh="onRefresh" @refresherrestore="onRestore">

			<!-- 骨架屏 -->
			<view class="skeleton-container" v-if="loading && users.length === 0">
				<view class="skeleton-item" v-for="i in 3" :key="i">
					<view class="skeleton-avatar skeleton-animate"></view>
					<view class="skeleton-info">
						<view class="skeleton-text skeleton-animate"></view>
						<view class="skeleton-subtext skeleton-animate"></view>
					</view>
				</view>
			</view>

			<!-- 用户列表 -->
			<view class="user-list" v-else-if="users.length > 0">
				<view class="user-item" v-for="user in users" :key="user.userId">
					<!-- 用户信息 -->
					<view class="user-info" @click="handleUserClick(user.userId)">
						<up-image :src="user.avatar" width="100rpx" height="100rpx" shape="circle"
							class="user-avatar"></up-image>
						<view class="user-details">
							<text class="user-nickname">{{ user.nickname }}</text>
							<text class="user-intro">{{ user.introduction || '这个人很懒，什么都没留下' }}</text>
						</view>
					</view>

					<!-- 关注按钮 -->
					<up-button :type="user.isFollowed ? 'default' : 'primary'" size="small"
						@click="handleFollow(user)" :plain="user.isFollowed" color="#36d399" class="follow-btn">
						{{ user.isFollowed ? '已关注' : '关注' }}
					</up-button>
				</view>

				<!-- 加载更多 -->
				<view class="load-more" v-if="hasMore">
					<up-loading-icon v-if="loadingMore" size="20" />
					<text v-else class="load-more-text">上拉加载更多</text>
				</view>
				<view class="no-more" v-else>
					<text class="no-more-text">没有更多了</text>
				</view>
			</view>

			<!-- 空状态 -->
			<view class="empty-state" v-else-if="!loading && users.length === 0">
				<up-icon :name="currentTab === 0 ? 'account' : 'account-fill'" size="80" color="#cccccc"></up-icon>
				<text class="empty-text">{{ currentTab === 0 ? '还没有关注任何人' : '还没有粉丝' }}</text>
				<text class="empty-hint">{{ currentTab === 0 ? '快去关注感兴趣的人吧～' : '发布优质内容吸引粉丝～' }}</text>
			</view>
		</scroll-view>
	</view>
</template>

<script setup>
	import {
		ref,
		reactive,
		onMounted
	} from 'vue';
	import {
		onLoad
	} from '@dcloudio/uni-app';
	import {
		mockGetUserInfo
	} from '../../server/mock.js';
	import showToast from '../../utils/showToast.js';

	// Tab 列表
	const tabList = ref([{
			name: '关注'
		},
		{
			name: '粉丝'
		}
	]);

	// 状态
	const currentTab = ref(0);
	const loading = ref(true);
	const refreshing = ref(false);
	const loadingMore = ref(false);
	const hasMore = ref(true);
	const users = ref([]);
	const pageNum = ref(1);
	const pageSize = ref(10);

	/**
	 * 加载用户列表
	 */
	const loadUsers = async () => {
		try {
			// 模拟获取关注/粉丝列表
			const userInfo = uni.getStorageSync('userInfo');
			if (!userInfo) {
				showToast('请先登录', 'none');
				setTimeout(() => {
					uni.navigateTo({
						url: '/pages/login/login'
					});
				}, 1000);
				return;
			}

			// 模拟数据
			const mockUsers = [{
					userId: 2,
					nickname: '小码农',
					avatar: 'https://picsum.photos/200/200?random=2',
					introduction: '计算机学院大三学生，喜欢编程和篮球',
					isFollowed: currentTab.value === 0
				},
				{
					userId: 3,
					nickname: '小书虫',
					avatar: 'https://picsum.photos/200/200?random=3',
					introduction: '文学院大二学生，爱读书、爱分享',
					isFollowed: currentTab.value === 0
				},
				{
					userId: 4,
					nickname: '运动达人',
					avatar: 'https://picsum.photos/200/200?random=4',
					introduction: '体育学院学生，热爱运动',
					isFollowed: currentTab.value === 0
				}
			];

			// 模拟分页
			const start = (pageNum.value - 1) * pageSize.value;
			const end = start + pageSize.value;
			const newData = mockUsers.slice(start, end);

			if (pageNum.value === 1) {
				users.value = newData;
			} else {
				users.value = [...users.value, ...newData];
			}

			hasMore.value = newData.length >= pageSize.value;
		} catch (error) {
			console.error('加载用户列表失败:', error);
			showToast('网络错误', 'error');
		} finally {
			loading.value = false;
		}
	};

	/**
	 * Tab 切换
	 */
	const handleTabChange = (e) => {
		// uview-plus 的 @change 事件可能传递对象或索引
		const index = typeof e === 'object' ? (e.index !== undefined ? e.index : e.name) : e;
		currentTab.value = Number(index);
		pageNum.value = 1;
		loading.value = true;
		hasMore.value = true;
		users.value = []; // 清空列表
		loadUsers();
	};

	/**
	 * 下拉刷新
	 */
	const onRefresh = async () => {
		refreshing.value = true;
		pageNum.value = 1;
		hasMore.value = true;

		try {
			await loadUsers();
		} finally {
			setTimeout(() => {
				refreshing.value = false;
			}, 300);
		}
	};

	/**
	 * 刷新恢复
	 */
	const onRestore = () => {
		refreshing.value = false;
	};

	/**
	 * 加载更多
	 */
	const loadMore = () => {
		if (!hasMore.value || loadingMore.value || loading.value) return;

		loadingMore.value = true;
		pageNum.value += 1;
		loadUsers().finally(() => {
			loadingMore.value = false;
		});
	};

	/**
	 * 点击用户
	 */
	const handleUserClick = (userId) => {
		uni.navigateTo({
			url: `/pages/user/userInfo?userId=${userId}`
		});
	};

	/**
	 * 关注/取消关注
	 */
	const handleFollow = async (user) => {
		try {
			// 切换关注状态
			user.isFollowed = !user.isFollowed;

			// 这里应该调用真实的关注/取消关注接口
			showToast(user.isFollowed ? '关注成功' : '已取消关注', 'success');

			// 如果是在"关注"tab 取消关注，移除该用户
			if (currentTab.value === 0 && !user.isFollowed) {
				setTimeout(() => {
					users.value = users.value.filter(u => u.userId !== user.userId);
				}, 500);
			}
		} catch (error) {
			console.error('关注操作失败:', error);
			showToast('操作失败', 'error');
			// 恢复状态
			user.isFollowed = !user.isFollowed;
		}
	};

	// 页面加载
	onLoad((option) => {
		// 支持从外部指定初始 tab（0: 关注, 1: 粉丝）
		if (option && option.tab !== undefined) {
			const tabIndex = parseInt(option.tab);
			currentTab.value = isNaN(tabIndex) ? 0 : tabIndex;
		}
		// 确保 currentTab 是数字类型
		if (typeof currentTab.value !== 'number') {
			currentTab.value = 0;
		}
		// 延迟加载，等待组件完全渲染
		setTimeout(() => {
			loadUsers();
		}, 100);
	});
</script>

<style lang="scss" scoped>
	.follow-page {
		min-height: 100vh;
		background-color: #f5f5f5;
		display: flex;
		flex-direction: column;

		.scroll-container {
			flex: 1;
			height: calc(100vh - 100rpx);
			padding: 20rpx;
		}
	}

	// 骨架屏
	.skeleton-container {
		.skeleton-item {
			display: flex;
			align-items: center;
			gap: 20rpx;
			background-color: #ffffff;
			border-radius: 16rpx;
			padding: 30rpx;
			margin-bottom: 20rpx;

			.skeleton-avatar {
				width: 100rpx;
				height: 100rpx;
				border-radius: 50%;
				background-color: #f0f0f0;
			}

			.skeleton-info {
				flex: 1;

				.skeleton-text {
					height: 28rpx;
					background-color: #f0f0f0;
					border-radius: 4rpx;
					margin-bottom: 12rpx;
					width: 60%;
				}

				.skeleton-subtext {
					height: 24rpx;
					background-color: #f0f0f0;
					border-radius: 4rpx;
					width: 80%;
				}
			}

			.skeleton-animate {
				animation: skeleton-loading 1.5s ease-in-out infinite;
				background: linear-gradient(90deg,
						#f0f0f0 25%,
						#e0e0e0 50%,
						#f0f0f0 75%);
				background-size: 200% 100%;
			}
		}
	}

	// 用户列表
	.user-list {
		.user-item {
			display: flex;
			align-items: center;
			justify-content: space-between;
			background-color: #ffffff;
			border-radius: 16rpx;
			padding: 30rpx;
			margin-bottom: 20rpx;

			.user-info {
				display: flex;
				align-items: center;
				gap: 20rpx;
				flex: 1;
				min-width: 0;

				.user-avatar {
					flex-shrink: 0;
				}

				.user-details {
					flex: 1;
					min-width: 0;

					.user-nickname {
						display: block;
						font-size: 30rpx;
						font-weight: 500;
						color: #333333;
						margin-bottom: 8rpx;
					}

					.user-intro {
						display: block;
						font-size: 24rpx;
						color: #999999;
						overflow: hidden;
						text-overflow: ellipsis;
						white-space: nowrap;
					}
				}
			}

			.follow-btn {
				flex-shrink: 0;
				width: 140rpx;
			}
		}
	}

	// 加载更多
	.load-more,
	.no-more {
		text-align: center;
		padding: 30rpx 0;

		.load-more-text,
		.no-more-text {
			font-size: 24rpx;
			color: #999999;
		}
	}

	// 空状态
	.empty-state {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 200rpx 0;
		gap: 20rpx;

		.empty-text {
			font-size: 28rpx;
			color: #999999;
		}

		.empty-hint {
			font-size: 24rpx;
			color: #cccccc;
		}
	}

	// 骨架屏动画
	@keyframes skeleton-loading {
		0% {
			background-position: 200% 0;
		}

		100% {
			background-position: -200% 0;
		}
	}
</style>

